from starlette.endpoints import HTTPEndpoint
from starlette.responses import JSONResponse
from database import Session, engine
import datetime
import logging
from dao import DaoPendingProSupSta
from wxpublic.wx_public_message import send_to_user, send_template_message
import config
import pendulum
from sqlalchemy.exc import SQLAlchemyError
from model.ModPowerSupplyBureauOperator import PowerSupplyBureauOperator
from model.ModPowerSupplyStationList import PowerSupplyStationList
from model.ModPendingProDet import PendingProDet


class PendingProSupSta(HTTPEndpoint):
    async def get(self, request):
        session = Session()
        try:
           bureauid = request.query_params["bureauid"]
           return DaoPendingProSupSta.get_pending_list(session, bureauid)
        finally:
            session.close()

class PendingProSupStaAll(HTTPEndpoint):
    def __init__(self, scope):
        self._logger = logging.getLogger('MONTH_REP')
        return super().__init__(scope)

    async def put(self, request):
        session = Session()
        try:
            dict_pending = await request.json()
            bureauid = dict_pending.get("bureauid")
            openid = request.user.open_id
            department_level = request.user.department_level
            #DaoPendingProSupSta.update_pending_info(session, bureauid, str(department_level))
            #session.commit()
            try:
                # 督办信息推送
                openid = dict_pending.get("openid")
                stationlist = session.query(PendingProDet.stationid).filter(
                    PendingProDet.bureauid == bureauid).distinct(PendingProDet.stationid).all()
                for statid in stationlist:
                    flag = DaoPendingProSupSta.get_check(session, bureauid, statid.stationid)
                    if flag == "2":
                        continue
                    DaoPendingProSupSta.update_pending_info_station(session, bureauid, statid.stationid,
                                                                    str(department_level))
                    session.commit()
                    target_auditor = session.query(PowerSupplyBureauOperator).filter(
                        PowerSupplyBureauOperator.power_supply_bureau == bureauid).filter(
                        PowerSupplyBureauOperator.stationid == statid.stationid).filter(
                        PowerSupplyBureauOperator.supervision_department == '9').all()
                    station_info = session.query(PowerSupplyStationList).filter(
                        PowerSupplyStationList.bureauid == bureauid).filter(
                        PowerSupplyStationList.stationid == statid.stationid).first()
                    userinfo = session.query(PowerSupplyBureauOperator).filter(
                        PowerSupplyBureauOperator.openid == openid).filter(
                        PowerSupplyBureauOperator.supervision_department <= '3').first()
                    user = ''
                    user_level = ''
                    if (userinfo.supervision_department == '1'):
                        user = '计量班长(专工)';
                        user_level = 'Ⅱ级'
                    elif (userinfo.supervision_department == '2'):
                        user = '营销主任';
                        user_level = 'Ⅲ级'
                    elif (userinfo.supervision_department == '3'):
                        user = '营销经理';
                        user_level = 'Ⅳ级'
                    for person in target_auditor:
                        send_template_message(person.openid,
                                              config.TEMPLATE_URGE,
                                              {
                                                  "first": {
                                                      "value": f"您好，您有采集待处理问题被提起督办！",
                                                      "color": "#000000"
                                                  },
                                                  "keyword1": {
                                                      "value": station_info.stationname,
                                                      "color": "#1736c0"
                                                  },
                                                  "keyword2": {
                                                      "value": "采集待处理工单",
                                                      "color": "#1736c0"
                                                  },
                                                  "keyword3": {
                                                      "value": f"{user}督办",
                                                      "color": "#1736c0"
                                                  },
                                                  "keyword4": {
                                                      "value": user_level,
                                                      "color": "#1736c0"
                                                  },
                                                  "keyword5": {
                                                      "value": pendulum.now().strftime('%Y-%m-%d %H:%M:%S'),
                                                      "color": "#1736c0"
                                                  },
                                                  "remark": {
                                                      "value": "请注意及时处理！",
                                                      "color": "#000000"
                                                  }
                                              })
            except SQLAlchemyError:
                self._logger.warn(f'审核状态提醒发送失败，未找到目标人员。')
            finally:
                session.rollback()
            return JSONResponse({"result": "1"})
        except Exception as e:
            session.rollback()
            return JSONResponse({"result": "0"})
        finally:
            session.close()

class PendingProSupStaSingle(HTTPEndpoint):
    def __init__(self, scope):
        self._logger = logging.getLogger('MONTH_REP')
        return super().__init__(scope)

    async def put(self, request):
        session = Session()
        try:
            dict_pending = await request.json()
            bureauid = dict_pending.get("bureauid")
            stationid = dict_pending.get("stationid")
            flag = DaoPendingProSupSta.get_check(session, bureauid, stationid)
            if flag == "2":
                session.rollback()
                return JSONResponse({"result": "2"})
            department_level = request.user.department_level
            DaoPendingProSupSta.update_pending_info_station(session, bureauid, stationid, str(department_level))
            session.commit()
        except Exception as e:
            session.rollback()
            return JSONResponse({"result": "0"})
        else:
            from sqlalchemy.exc import SQLAlchemyError
            try:
                # 督办信息推送
                openid = dict_pending.get("openid")
                target_auditor = session.query(PowerSupplyBureauOperator).filter(
                    PowerSupplyBureauOperator.power_supply_bureau == bureauid).filter(
                    PowerSupplyBureauOperator.stationid == stationid).filter(
                    PowerSupplyBureauOperator.supervision_department == '9').all()
                station_info = session.query(PowerSupplyStationList).filter(
                    PowerSupplyStationList.bureauid == bureauid).filter(
                    PowerSupplyStationList.stationid == stationid).first()
                userinfo = session.query(PowerSupplyBureauOperator).filter(
                    PowerSupplyBureauOperator.openid == openid).filter(
                    PowerSupplyBureauOperator.supervision_department <= '3').first()
                user = ''
                user_level = ''
                if (userinfo.supervision_department == '1'):
                    user = '计量班长(专工)';
                    user_level = 'Ⅱ级'
                elif (userinfo.supervision_department == '2'):
                    user = '营销主任';
                    user_level = 'Ⅲ级'
                elif (userinfo.supervision_department == '3'):
                    user = '营销经理';
                    user_level = 'Ⅳ级'
                for person in target_auditor:
                    send_template_message(person.openid,
                                  config.TEMPLATE_URGE,
                                  {
                                      "first": {
                                          "value": f"您好，您有采集待处理问题被提起督办！",
                                          "color": "#000000"
                                      },
                                      "keyword1": {
                                          "value": station_info.stationname,
                                          "color": "#1736c0"
                                      },
                                      "keyword2": {
                                          "value": "采集待处理工单",
                                          "color": "#1736c0"
                                      },
                                      "keyword3": {
                                          "value": f"{user}督办",
                                          "color": "#1736c0"
                                      },
                                      "keyword4": {
                                          "value": user_level,
                                          "color": "#1736c0"
                                      },
                                      "keyword5": {
                                          "value": pendulum.now().strftime('%Y-%m-%d %H:%M:%S'),
                                          "color": "#1736c0"
                                      },
                                      "remark": {
                                          "value": "请注意及时处理！",
                                          "color": "#000000"
                                      }
                                  })
            except SQLAlchemyError:
                self._logger.warn(f'审核状态提醒发送失败，未找到目标人员。')
            finally:
                session.rollback()
            return JSONResponse({"result": "1"})
        finally:
            session.close()